// wordLearningService.js - 单词学习服务

class WordLearningService {
  constructor() {
    // 初始化数据管理器 - 使用全局实例
    const app = getApp();
    this.wordDataManager = app.globalData.wordDataManager;
    this.currentBook = null;
    this.words = [];
  }

  /**
   * 初始化学习服务
   */
  init() {
    // 可以在这里执行任何必要的初始化
    console.log('单词学习服务初始化');
  }

  /**
   * 加载单词数据
   * @param {string} startWordId - 可选，从指定单词ID开始学习
   * @returns {Promise} 加载结果Promise
   */
  loadWordsData(startWordId = null) {
    return new Promise((resolve, reject) => {
      try {
        // 获取所有词书，找到当前激活的词书（active: 1）
        const allBooks = this.wordDataManager.getAllBooks();
        const activeBook = allBooks.find(book => book.active === 1);

        if (!activeBook) {
          console.warn('没有找到激活的词书');
          reject(new Error('请先选择一个词书进行学习'));
          return;
        }

        // 获取当前激活词书的单词列表
        const bookWords = this.wordDataManager.getWordsByBookId(activeBook.id);

        if (bookWords.length === 0) {
          console.warn('激活词书没有单词');
          reject(new Error(`词书"${activeBook.name}"没有单词，请添加单词后再学习`));
          return;
        }

        // 将词书单词转换为页面所需格式
        this.words = bookWords.map(word => {
          // 获取学习信息
          const learnCount = this.wordDataManager.getWordLearnCount(word.id);
          const lastLearnTime = this.wordDataManager.getWordLastLearnTime(word.id);
          const isMemorized = this.wordDataManager.getWordMemorizedStatus(word.id);
          
          return {
            id: word.id,
            english: word.english,
            phonetic: word.phonetic || '',
            chinese: word.chinese,
            example: word.example || '',
            examples: word.examples || [],
            pronunciation: word.pronunciation || null, // 添加发音信息
            phrases: word.phrases || [], // 添加词组信息
            synonyms: word.synonyms || [], // 添加近义词信息
            antonyms: word.antonyms || [], // 添加反义词信息
            individual: word.individual || {}, // 添加个性化数据
            learnCount: learnCount,
            lastLearnTime: lastLearnTime,
            isMemorized: isMemorized,
            isLearned: learnCount > 0
          };
        });

        this.currentBook = activeBook;

        let startIndex = 1;
        let currentWord = this.words[0] || {};
        
        // 如果提供了startWordId，找到该单词的位置
        if (startWordId) {
          const wordIndex = this.words.findIndex(word => word.id === startWordId);
          if (wordIndex !== -1) {
            startIndex = wordIndex + 1; // +1因为currentWordIndex从1开始
            currentWord = this.words[wordIndex];
          }
        }

        const result = {
          words: this.words,
          unitName: activeBook.name,
          currentWord: currentWord,
          startIndex: startIndex
        };

        resolve(result);
      } catch (error) {
        console.error('加载单词数据失败:', error);
        reject(new Error('加载单词数据失败，请稍后重试'));
      }
    });
  }

  /**
   * 获取单词数据
   * @returns {Array} 单词数组
   */
  getWords() {
    return this.words;
  }

  /**
   * 获取当前词书信息
   * @returns {Object|null} 词书信息
   */
  getCurrentBook() {
    return this.currentBook;
  }

  /**
   * 标记单词为已学/未学
   * @deprecated 此方法已不再使用，学习状态通过learnCount>0判断
   * @param {number} wordId - 单词ID
   * @param {boolean} isLearned - 是否已学
   * @returns {boolean} 操作是否成功
   */
  markWordAsLearned(wordId, isLearned) {
    try {
      console.warn('markWordAsLearned方法已不再使用，学习状态通过learnCount>0判断');
      
      // 找到对应的单词
      const wordIndex = this.words.findIndex(word => word.id === wordId);
      if (wordIndex === -1) {
        console.warn(`未找到ID为${wordId}的单词`);
        return false;
      }

      // 获取当前词书ID
      const currentBook = this.getCurrentBook();
      if (!currentBook || !currentBook.id) {
        console.error('当前没有有效的词书信息');
        return false;
      }

      // 如果标记为已学，增加学习次数；如果标记为未学，重置学习次数为0
      let result = false;
      if (isLearned) {
        // 增加学习次数
        result = this.wordDataManager.incrementWordLearnCount(wordId, currentBook.id) > 0;
      } else {
        // 重置学习次数为0
        // 注意：这里没有直接的API来重置学习次数，需要通过WordLearningDataManager来实现
            try {
              const app = getApp();
              const wordLearningDataManager = app.globalData.wordLearningDataManager;
              wordLearningDataManager.updateLearningData(wordId, {
            learnCount: 0,
            lastLearnTime: new Date().toISOString()
          });
          result = true;
        } catch (error) {
          console.error('重置学习次数失败:', error);
          result = false;
        }
      }

      return result;
    } catch (error) {
      console.error('标记单词状态失败:', error);
      return false;
    }
  }

  /**
   * 获取单词学习进度
   * @returns {Object} 学习进度信息
   */
  getLearningProgress() {
    const totalWordsCount = this.words.length;
    const learnedCount = this.words.filter(word => word.isLearned).length;
    const progressPercentage = totalWordsCount > 0 ? (learnedCount / totalWordsCount) * 100 : 0;

    return {
      totalWordsCount,
      learnedCount,
      progressPercentage
    };
  }

  /**
   * 加载发音设置
   * @returns {Object} 发音设置
   */
  loadPronunciationSettings() {
    try {
      const pronunciationType = this.wordDataManager.getPronunciationType();
      const playbackSpeed = this.wordDataManager.getPlaybackSpeed();
      const autoPlay = this.wordDataManager.getAutoPlay();

      return {
        pronunciationType,
        playbackSpeed,
        autoPlay
      };
    } catch (error) {
      console.error('加载发音设置失败:', error);
      // 返回默认设置
      return {
        pronunciationType: 'american',
        playbackSpeed: 1.0,
        autoPlay: true
      };
    }
  }

  /**
   * 保存发音设置
   * @param {string} type - 设置类型
   * @param {any} value - 设置值
   * @returns {boolean} 保存是否成功
   */
  savePronunciationSetting(type, value) {
    try {
      let success = false;

      switch(type) {
        case 'pronunciationType':
          success = this.wordDataManager.setPronunciationType(value);
          break;
        case 'playbackSpeed':
          // 验证倍速范围
          const validSpeed = Math.max(0.5, Math.min(2.0, parseFloat(value)));
          success = this.wordDataManager.setPlaybackSpeed(validSpeed);
          break;
        case 'autoPlay':
          success = this.wordDataManager.setAutoPlay(value);
          break;
        case 'loopPlay':
          success = this.wordDataManager.setLoopPlay(value);
          break;
        case 'loopCount':
          // 验证循环次数范围，不设置次数则为无限循环
          const validCount = value === '' ? '' : Math.max(1, Math.min(100, parseInt(value) || 1));
          success = this.wordDataManager.setLoopCount(validCount);
          break;
        case 'loopInterval':
          // 验证循环间隔范围
          const validInterval = Math.max(0.5, Math.min(10, parseFloat(value) || 2));
          success = this.wordDataManager.setLoopInterval(validInterval);
          break;
        default:
          console.warn(`未知的设置类型: ${type}`);
          return false;
      }

      return success;
    } catch (error) {
      console.error('保存发音设置失败:', error);
      return false;
    }
  }

  /**
   * 更新全局学习数据
   */
  updateGlobalLearningData() {
    try {
      const app = getApp();
      if (app.globalData.learningData && app.globalData.learningData.vocabulary) {
        // 这里应该根据实际情况更新全局数据
        console.log('更新全局学习数据');
        // 实际项目中这里会有具体的更新逻辑
      }
    } catch (error) {
      console.error('更新全局学习数据失败:', error);
    }
  }

  /**
   * 计算学习统计数据
   * @param {number} startTime - 学习开始时间
   * @returns {Object} 学习统计数据
   */
  calculateLearningStats(startTime) {
    const endTime = new Date().getTime();
    const studyDuration = Math.floor((endTime - startTime) / 60000);
    const progress = this.getLearningProgress();
    
    // 简化处理，实际项目中应该有更复杂的计算逻辑
    const accuracy = 100;
    
    return {
      studyTime: `${studyDuration}分钟`,
      accuracy,
      ...progress
    };
  }
}

module.exports = WordLearningService;